/**
 * 图片转BASE64
 * @param file
 * @returns {Promise<iconBase64>}
 */
export function imageToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    let iconBase64 = ''
    reader.readAsDataURL(file[0])
    reader.onload = () => {
      iconBase64 = reader.result
      resolve(iconBase64)
    }
  })
}

/**
 * 获取图片尺寸
 * @param file
 */
export function imgSize(url) {
  return new Promise((resolve, reject) => {
    const img = new Image() // 手动创建一个Image对象
    img.src = url
    let height = 210
    img.onload = function() {
      height = (375 / img.width) * img.height
      resolve(height)
    }
  })
}

/**
 * 生成随机UUID(36位)
 * @returns {Promise<unknown>}
 */
export function uuid() {
  let uuid = ''
  const s = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4'
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
  s[8] = s[13] = s[18] = s[23] = '-'

  uuid = s.join('')
  return uuid
}

/**
 * 递归复制(深拷贝)
 * @param obj
 * @returns {[]|{}}
 */
export function deepCopy(obj) {
  const result = Array.isArray(obj) ? [] : {}
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        result[key] = deepCopy(obj[key]) // 递归复制
      } else {
        result[key] = obj[key]
      }
    }
  }
  return result
}
